/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef CAFFE2_OPERATORS_ROW_MUL_H_
#define CAFFE2_OPERATORS_ROW_MUL_H_

#include "caffe2/core/context.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
#include "caffe2/utils/math.h"

namespace caffe2 {

// A hacky version of Mul with broadcast
// RowMul([mat, w], [output])
template <typename T, class Context>
class RowMulOp : public Operator<Context> {
 public:
  USE_OPERATOR_CONTEXT_FUNCTIONS;
  USE_SIMPLE_CTOR_DTOR(RowMulOp);

  bool RunOnDevice() override {
    auto& mat = Input(0);
    auto& w = Input(1);
    auto* output = Output(0);

    output->ResizeLike(mat);
    T* output_data = output->template mutable_data<T>();
    const T* mat_data = mat.template data<T>();
    const T* w_data = w.template data<T>();

    // Dimension checking
    CAFFE_ENFORCE_EQ(
        w.size(),
        mat.dim32(0),
        "Length of w should be equal to the first dim of mat");

    auto block_size = mat.size_from_dim(1);
    for (int i = 0; i < w.size(); i++) {
      size_t offset = i * block_size;
      for (int j = 0; j < block_size; j++) {
        output_data[offset + j] = mat_data[offset + j] * w_data[i];
      }
    }

    return true;
  }
};

// A hacky version
template <typename T, class Context>
class ReduceTailSumOp : public Operator<Context> {
 public:
  USE_OPERATOR_CONTEXT_FUNCTIONS;
  USE_SIMPLE_CTOR_DTOR(ReduceTailSumOp);

  bool RunOnDevice() override {
    auto& mat = Input(0);
    auto* output = Output(0);

    int N = mat.dim32(0);
    int block_size = mat.size_from_dim(1);

    output->Resize(N);
    T* output_data = output->template mutable_data<T>();
    const T* mat_data = mat.template data<T>();

    for (int i = 0; i < N; i++) {
      output_data[i] = 0;
      size_t offset = i * block_size;
      for (int j = 0; j < block_size; j++) {
        output_data[i] += mat_data[offset + j];
      }
    }
    return true;
  }
};

} // namespace caffe2

#endif // CAFFE2_OPERATORS_ROW_MUL_H_
